import requests

import settings


class RequestByProxyPool:
    __server = settings.PROXY_CONN

    def response(self, url):
        retry_count = 5

        try:
            r = requests.get(url=url, headers=settings.Headers, timeout=20, stream=True)
            return r, r.status_code
        except Exception:
            proxy = self.get_proxy().get('proxy')
            while retry_count > 0:
                try:
                    r = requests.get(url=url, headers=settings.Headers, timeout=20,
                                     proxies={'http': 'http://{}'.format(proxy)}, stream=True)
                    return r, r.status_code
                except Exception:
                    retry_count -= 1
                    self.delete_proxy(proxy)
                    return None, 404

    def get_proxy(self):
        return requests.get(self.__server + '/get?type=https').json()

    def delete_proxy(self, proxy):
        requests.get(self.__server + '/delete/?proxy={}'.format(proxy))
